#import "ImageLoader.h"

@interface ImageLoader ()

@property (nonatomic, strong) NSCache *imageCache;

@end

@implementation ImageLoader

+ (instancetype)sharedInstance {
    static ImageLoader *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[ImageLoader alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _imageCache = [[NSCache alloc] init];
    }
    return self;
}

- (void)loadImageFromURL:(NSURL *)url imageView:(UIImageView *)imageView completion:(void (^)(UIImage *image, NSError *error))completion {
    
    UIImage *cachedImage = [self.imageCache objectForKey:url];
    if (cachedImage) {
//        imageView.image = cachedImage;
        dispatch_async(dispatch_get_main_queue(), ^{
            imageView.image = cachedImage;
                   });
        completion(cachedImage, nil);
        return;
    }

    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (!error && data) {
            UIImage *image = [UIImage imageWithData:data];
            if(image){
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = image;
                           });
                [self.imageCache setObject:image forKey:url];
            }
            completion(image, nil);
        } else {
            completion(nil, error);
        }
    }];
    [task resume];
}
- (NSData *)compressImage:(UIImage *)image toLessThanSize:(NSUInteger)targetSize {
    CGFloat compressionQuality = 1.0;
    NSData *imageData = UIImageJPEGRepresentation(image, compressionQuality);
    while ([imageData length] > targetSize && compressionQuality > 0) {
        compressionQuality -= 0.1;
        imageData = UIImageJPEGRepresentation(image, compressionQuality);
    }
    return imageData;
}
@end
